package chat_server;

// -----------------------------------------------------------------------------
// Importansweisungen
import for_all.PopUp;
import java.io.*;
import java.net.*;

public class Server extends Thread {
    
    // -------------------------------------------------------------------------
    // Variablendeklarationen
    private ServerSocket server;
    public ManageUser users;
    public ManageRooms rooms;
    private ServerGui serverGUI;
    
    
    // -------------------------------------------------------------------------
    // Konstruktor
    public Server(int port, ServerGui serverGUI) throws IOException {
        
        this.server = new ServerSocket(port);
        this.users  = new ManageUser(serverGUI);
        this.rooms  = new ManageRooms(serverGUI);
        this.serverGUI = serverGUI;
    }
    
    
    // -------------------------------------------------------------------------
    // Abhören der eingehenden allgemeinen Netzwerkkommunikation (LogIn)
    @Override
    public void run() {
        
        while (!Server.interrupted()) { // Solange, bis der Server gestoppt wird
            
            Socket client;
            
            try {
                client = this.server.accept();
                new ClientHandler(client, this.users, this.rooms).start();
           
            } catch (IOException ex) {
                PopUp fail = new PopUp(serverGUI, "IOException in run vom Server: " + ex.getMessage(), PopUp.MessageTyp.Error);
            }
        } 
    }
    
    
    // -------------------------------------------------------------------------
    // Raum erstellen
    public void CreateRoom(String roomName) {
        this.rooms.createRoom(roomName);
        this.users.informAllUserAboutNewRoom(roomName);
    }
    
    
    // -------------------------------------------------------------------------
    // Raum löschen
    public void DeleteRoom(String roomName) {
        this.rooms.deleteRoom(roomName);
        this.users.informAllUserAboutDeletedRoom(roomName);
    }
    
    
    // -------------------------------------------------------------------------
    // Raumname ändern
    public void ChangeRoomName(String oldName, String newName) {
        this.rooms.changeRoomName(oldName, newName);
        this.users.informAllUserAboutRoomNameChanged(oldName, newName);
    }
    
    
    // -------------------------------------------------------------------------
    // Server stoppen
    public void stopServer() {
        this.interrupt();
    }

}